#!/usr/bin/python3
# --*-- coding: utf-8 --*--
# @Author: zheng dandan
# @Email: cha.baby@qq.com
# @Time: 2021/5/21 16:20
# @File: main.py
# @Software: PyCharm
import os
import barcode
from barcode.writer import ImageWriter


# 读文件
def get_bn_list(file_name):
	bns = []
	try:
		with open(file_name) as file_resource:
			for line in file_resource:
				bns.append(line.strip())
		return bns
	except FileNotFoundError:
		print('File Not Found!')
		return None


# 生成二维码
def gen_barcode(bn, path):
	name = barcode.generate(u'code128', bn, writer=ImageWriter(), output='{}\{}'.format(path, bn))
	# print(name)


def clear_directory(dir):
	try:
		for root, dirs, files in os.walk(dir, topdown=False):
			for name in files:
				os.remove(os.path.join(root, name))
	except:
		return False
	return True


if __name__ == '__main__':
	bn_file = r'bn.txt'
	bns = get_bn_list(bn_file)
	barcode_directory = 'barcodes'
	# 清除已有的二维码
	if not clear_directory(barcode_directory):
		print("barcode in {} is not clear".format(barcode_directory))
	if bns != None:
		for bn in bns:
			gen_barcode(bn, barcode_directory)
			print('{} is generated!'.format(bn))
		print('All bn code get de qrcode!!!')
	exit(0)


